package controller

import (
	"GoAdmin/common"
	"GoAdmin/models"
	. "GoAdmin/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/go-xorm/xorm"
	"github.com/spf13/cast"
	"log"
	"net/http"
	"strconv"
	"time"
	"xorm.io/builder"
)

var DrivingCarTypeMap = map[string]int64{
	"A1": 1,
	"A2": 2,
	"A3": 3,
	"B1": 4,
	"B2": 5,
	"C1": 6,
	"C2": 7,
	"C3": 8,
	"C4": 9,
	"C5": 10,
	"D":  11,
	"E":  12,
	"F":  13,
	"M":  14,
	"N":  15,
	"P":  16,
}

func CoachInformation(c *gin.Context) {
	var (
		name     string
		phone    string
		idNumber string
		schoolId string
	)
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultPostForm("pageSize", "15"))
	offset := (page - 1) * pageSize
	user, _ := common.GetCtxUser(c)
	filter := builder.NewCond()
	if user.Type == "0" || user.Type == "1" {
		//管理用户查询全部
	} else {
		if user.Province != "" {
			filter = filter.And(builder.Eq{"sl.province": user.Province})
		}
		if user.City != "" {
			filter = filter.And(builder.Eq{"sl.city": user.City})
		}
		if user.District != "" {
			filter = filter.And(builder.Eq{"sl.district": user.District})
		}
	}
	if user.Type == "3" {
		//同一个地区双代理
		filter = filter.And(builder.Eq{"sl.config": user.SchoolList})
	}
	if schoolId = c.PostForm("school_id"); schoolId != "" {
		filter = filter.And(builder.Eq{"ch.school_id": schoolId})
	}
	if name = c.PostForm("name"); name != "" {
		filter = filter.And(builder.Eq{"u.name": name})
	}
	if phone = c.PostForm("phone"); phone != "" {
		filter = filter.And(builder.Eq{"u.phone": phone})
	}
	if idNumber = c.PostForm("id_number"); idNumber != "" {
		filter = filter.And(builder.Eq{"u.id_number": idNumber})
	}
	filter = filter.And(builder.Eq{"u.type": "3"}).And(builder.Eq{"ch.isused": "1"}).And(builder.Eq{"u.isused": "1"})
	count, list, _ := new(models.Coach).GetCoachByFilter(filter, pageSize, offset)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": gin.H{"list": list, "count": count}})
	return
}

func CoachDetail(c *gin.Context) {
	var (
		coachId string
	)
	log.Println(c.PostForm("coach_id"))
	if coachId = c.PostForm("coach_id"); coachId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	has, coachDetail, _ := new(models.Coach).GetCoachDetailInfo(coachId)
	if !has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "查询成功", "data": coachDetail})
	return
}

func CoachRecordList(c *gin.Context) {
	var (
		coachId string
	)
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultPostForm("pageSize", "15"))
	offset := (page - 1) * pageSize
	if coachId = c.PostForm("coach_id"); coachId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	coachRecord, count, _ := new(models.LearnRecord).GetCoachRecordList(coachId, pageSize, offset)

	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "查询成功", "data": gin.H{"list": coachRecord, "count": count}})
	return
}

func CoachLogout(c *gin.Context) {
	var (
		id string
	)
	if id = c.PostForm("id"); id == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	if !new(models.Coach).Logout(id) {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "处理失败", "data": nil})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "处理成功", "data": nil})
	return
}

func CoachDelete(c *gin.Context) {
	var (
		id       string
		url      string
		ret_map  map[string]interface{}
		req_type int64
	)
	id = c.PostForm("coach_id")
	info, coach, err := new(models.Coach).GetDeleteCoachInfo(id)
	if err != nil || !info {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询教练员不存在或者信息错误"})
		return
	}
	apiMethod := "DELETE"
	req_type = 2
	if coach.Province == "370000" || coach.Province == "340000" || coach.Province == "420000" {
		apiMethod = "GET"
	}
	if coach.LoginStatus == "1" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该教练是已登录状态,退出后重试"})
		return
	}
	if coach.RecordStatus == "0" {
		if coach.Isused == "1" {
			if !new(models.Coach).DelById(coach.Id) {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败"})
				return
			}
			var user models.User
			if user, err = new(models.User).GetById(strconv.FormatInt(int64(coach.UserId), 10)); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			if !user.Delete() {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除用户信息失败"})
				return
			}
		}
	} else {
		if coach.Isused == "1" {
			if url, err = GetSignURL("coach-"+coach.InstitutionCode, nil, req_type, coach.Province, coach.City); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			// 请求运管
			var api_log models.ApiLog
			api_log.Url = url
			api_log.Param = ""
			api_log.Method = "POST"
			api_log.UserId, _ = strconv.Atoi(c.PostForm("user_id"))
			api_log.Time = time.Now()
			if ret_map, err = APIReq(url, nil, apiMethod); err != nil {
				result, _ := json.Marshal(ret_map)
				api_log.Result = string(result)
				api_log.Add()
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			result, _ := json.Marshal(ret_map)
			api_log.Result = string(result)
			api_log.Add()
			log.Println(ret_map)
			if cast.ToString(ret_map["errorcode"]) == "1" {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "省平台：" + cast.ToString(ret_map["message"])})
				return
			}
			if c.PostForm("province") == "340000" {
				school, err := new(models.School).GetSchoolById(fmt.Sprintf("%d", coach.SchoolId))
				if err != nil {
					log.Println("GetSchoolById", cast.ToString(coach.SchoolId))
				}
				data := map[string]interface{}{
					"inscode":  school.InstitutionCode,
					"coachnum": coach.InstitutionCode,
				}
				if _, err := AnHuiServiceAPIURLRequest("driverBA/delete.do", "POST", school.InstitutionCode, data); err != nil {
					log.Println("coach_code", coach.InstitutionCode)
				}
			}
			//设为已删除及离职状态
			if !new(models.Coach).DelById(coach.Id) {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除教练失败"})
				return
			}
			var user models.User
			if user, err = new(models.User).GetById(strconv.FormatInt(int64(coach.UserId), 10)); err != nil {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
			if !user.Delete() {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除用户信息失败"})
				return
			}
		}
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除教练成功"})
		return
	}
}

func PostRequest(reqUrl string, data map[string][]string) (*http.Response, error) {
	request, err := http.PostForm(reqUrl, data)
	if err != nil {
		return nil, err
	}
	return request, err
}
func CoachAdd(c *gin.Context) {
	var (
		err      error
		req_type int64
		age      int
	)
	coach := new(models.Coach)
	user := new(models.User)
	portrait := new(models.Portrait)
	finger := new(models.Finger)
	if c.PostForm("city") == "130100" {
		//石家庄
		req_type = 3
	} else {
		req_type = 2
	}
	if err = c.ShouldBind(coach); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if err = c.ShouldBind(user); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if err = c.ShouldBind(portrait); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if c.PostForm("city") == "130100" {
		//石家庄判断   实操添加60判断
		if coach.Subject == "2" {
			if user.IdType == "1" {
				age = GetAge(user.IdNumber)
				fmt.Println(age)
				if age > 60 {
					filter := builder.NewCond()
					filter = filter.And(builder.Eq{"id_number": user.IdNumber})
					filter = filter.And(builder.Eq{"type": "3"})
					filter = filter.And(builder.Eq{"isused": "0"})
					if has, _, _ := new(models.User).GetUserExists(filter); has {
						c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "年龄超过60岁，不能录入"})
						return
					} else {

					}
				}
			}
		}
	} else {
	}
	user.Type = "3"
	coach.ApprovalStatus = "0"
	coach.RecordStatus = "0"
	coach.LoginStatus = "0"
	coach.Isused = "1"
	coach.AddTime = time.Now()
	id_num := user.IdNumber
	if len([]rune(id_num)) <= 12 {
		user.Password = Md5("123456")
	} else {
		user.Password = Md5(id_num[12:18])
	}
	user.Isused = "1"
	coach.LicenceGrantDate, _ = time.Parse("2006-01-02", c.PostForm("licence_grant_date"))
	coach.EntryDate, _ = time.Parse("2006-01-02", c.PostForm("entry_date"))
	if c.PostForm("portrait_code") == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请上传照片"})
		return
	}
	if c.PostForm("image_url") == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请上传照片"})
		return
	}
	if err = user.CheckData(1); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	var engine *xorm.Engine
	engine = models.Engine
	session := engine.NewSession()
	defer session.Close()
	err = session.Begin()
	_, err = session.Table("dts_user").Insert(user)
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	portrait.UserId = user.Id
	portrait.AddTime = time.Now()
	portrait.TerminalId = 0
	_, err = session.Table("dts_portrait").Insert(portrait)
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if err = new(models.Coach).BaiduCheck(portrait.ImageUrl, user, c.PostForm("school_id")); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if coach.FingerId != 0 {
		if finger, err = new(models.Finger).GetFingerById(coach.FingerId); err == nil {
			finger.InstitutionCode, _ = Fileid(finger.ImageUrl, "coachfp", req_type, c.PostForm("province"), c.PostForm("city"))
		}
	}
	coach.PortraitId = portrait.Id
	coach.UserId = user.Id
	if coach.DrivingCarType != "" && coach.TeachingCarType != "" {
		if DrivingCarTypeMap[coach.DrivingCarType] <= DrivingCarTypeMap[coach.TeachingCarType] {

		} else {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "准驾车型与准教车型不匹配"})
			return
		}
	}
	if coach.TeachingCarTypes == "" {
		coach.TeachingCarTypes = coach.TeachingCarType
	}
	if coach.DrivingCarTypes == "" {
		coach.DrivingCarTypes = coach.DrivingCarType
	}
	coach.SchoolId, _ = strconv.Atoi(c.PostForm("school_id"))
	_, err = session.Table("dts_coach").Insert(coach)
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	err = session.Commit()
	if err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "添加教练成功"})
	return

}

func GetAge(idCard string) (age int) {
	var mapmou = map[string]int{"January": 1, "february": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}
	now := time.Now()
	now_year := now.Year()                               // 年
	now_mo := mapmou[now.Month().String()]               // 月
	now_day := now.Day()                                 // 日
	idcard_year, _ := strconv.Atoi(Substr(idCard, 6, 4)) // 年
	idcard_mo, _ := strconv.Atoi(Substr(idCard, 10, 2))  // 月
	idcard_day, _ := strconv.Atoi(Substr(idCard, 12, 2)) // 日
	age = now_year - idcard_year                         // 如果计算虚岁需这样：age := now_year - idcard_year+1
	if now_year < idcard_year {
		age = 0
	} else {
		if now_mo < idcard_mo {
			age = age - 1
		} else {
			if now_day < idcard_day {
				age = age - 1
			}
		}
	}
	return age
}

func RecordCoach(c *gin.Context) {
	var (
		coachId string
		code    string
	)
	coachId = c.PostForm("coach_id")
	valid := validation.Validation{}
	valid.Required(coachId, "coach_id").Message("未选择教练")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	} else {
		coach, err := new(models.Coach).GetCoachByID(coachId)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
			return
		}
		if coach.ApprovalStatus == "1" {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "已审核通过教练员不可以备案"})
			return
		}
		info, err := new(models.Coach).GetCoachInfo(coachId)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
			return
		}
		coachData := map[string]string{
			"school_code":   info.SchoolCode,
			"portrait_code": info.PhotoCode,
			"province":      info.Province,
			"city":          info.City,
			"name":          info.Name,
			"sex":           info.Sex,
			"phone":         info.Phone,
			"idNumber":      info.IdNumber,
			"address":       info.Address,
			"image_url":     info.ImageUrl,
			"finger":        "",
		}
		if code, err = coach.GetInstitution(coachData); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		coach.InstitutionCode = code
		//备案
		if err = coach.RecordCoach(coachData); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		//更新
		coach.RecordStatus = "1"
		coach.RecordStatus2 = "0"
		coach.ApprovalStatus = "0"
		if _, err = coach.Edit("institution_code", "record_status", "approval_status", "record_status2"); err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "教练员备案成功"})
		return
	}
}

//
//func DeleteCoach(c *gin.Context) {
//	var (
//		coachId string
//	)
//	coachId = c.PostForm("coach_id")
//	valid := validation.Validation{}
//	valid.Required(coachId, "coach_id").Message("未选择教练")
//	if valid.HasErrors() {
//		for _, err := range valid.Errors {
//			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
//			return
//		}
//	} else {
//		//coach, err := new(models.Coach).GetCoachByID(coachId)
//		//if err != nil {
//		//	c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
//		//	return
//		//}
//	}
//}
